package com.atguigu.gmall.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.app.BaseAppV2;
import com.atguigu.gmall.realtime.bean.VisitorStats;
import com.atguigu.gmall.realtime.util.MySinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.Map;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/3/22 15:35
 */
public class DWSVisitorStatsApp extends BaseAppV2 {
    public static void main(String[] args) {
        new DWSVisitorStatsApp().init(30001, 2, "DWSVisitorStatsApp", "DWSVisitorStatsApp",
                                      "dwd_page_log", "dwm_uv", "dwm_user_jump_detail");
    }
    
    @Override
    public void run(StreamExecutionEnvironment env,
                    Map<String, DataStreamSource<String>> sourceStreams) {
        // 1. 把3个流合并成一个流  union
        final DataStream<VisitorStats> visitorStatsDataStream = parseSteamsUnionOneStream(sourceStreams);
        // 2. 按照维度做聚合
        final SingleOutputStreamOperator<VisitorStats> statsStream  = aggregateByDims(visitorStatsDataStream);
        // 3. 写入到ClickHouse中
        sink2ClickHouse(statsStream);
        
    
    }
    
    private void sink2ClickHouse(SingleOutputStreamOperator<VisitorStats> statsStream) {
        statsStream.addSink(MySinkUtil.getClickHouseSink("gmall2021", "visitor_stats_2021", VisitorStats.class));
    }
    
    private SingleOutputStreamOperator<VisitorStats> aggregateByDims(DataStream<VisitorStats> visitorStatsDataStream) {
        final SingleOutputStreamOperator<VisitorStats> result = visitorStatsDataStream
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<VisitorStats>forBoundedOutOfOrderness(Duration.ofSeconds(5))
                    .withTimestampAssigner((vs, ts) -> vs.getTs())
            )
            // 按照维度分组
            .keyBy(vs -> vs.getVc() + "_" + vs.getCh() + "_" + vs.getAr() + "_" + vs.getIs_new())
            .window(TumblingEventTimeWindows.of(Time.seconds(10)))
            .reduce(
                new ReduceFunction<VisitorStats>() {
                    @Override
                    public VisitorStats reduce(VisitorStats value1, VisitorStats value2) throws Exception {
                        value1.setUv_ct(value1.getUv_ct() + value2.getUv_ct());
                        value1.setPv_ct(value1.getPv_ct() + value2.getPv_ct());
                        value1.setSv_ct(value1.getSv_ct() + value2.getSv_ct());
                        value1.setUj_ct(value1.getUj_ct() + value2.getUj_ct());
                        value1.setDur_sum(value1.getDur_sum() + value2.getDur_sum());
                        return value1;
                    }
                },
                new ProcessWindowFunction<VisitorStats, VisitorStats, String, TimeWindow>() {
                    
                    private SimpleDateFormat sdf;
                    
                    @Override
                    public void open(Configuration parameters) throws Exception {
                        sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    }
                    
                    @Override
                    public void process(String key,
                                        Context ctx,
                                        Iterable<VisitorStats> elements,
                                        Collector<VisitorStats> out) throws Exception {
                        // 补齐 窗口开始时间和结束时间
                        final VisitorStats vs = elements.iterator().next();
                        vs.setStt(sdf.format(ctx.window().getStart()));
                        vs.setEdt(sdf.format(ctx.window().getEnd()));
                        out.collect(vs);
                    }
                }
            );
        
        return result;
        
    }
    
    private DataStream<VisitorStats> parseSteamsUnionOneStream(Map<String, DataStreamSource<String>> sourceStreams) {
        final DataStreamSource<String> pageStream = sourceStreams.get("dwd_page_log");
        final DataStreamSource<String> uvStream = sourceStreams.get("dwm_uv");
        final DataStreamSource<String> userJumpStream = sourceStreams.get("dwm_user_jump_detail");
        
        // 标记uv
        final SingleOutputStreamOperator<VisitorStats> uvStatsStream = uvStream.map(json -> {
            final JSONObject obj = JSON.parseObject(json);
            final JSONObject commonObj = obj.getJSONObject("common");
            return new VisitorStats("", "",
                                    commonObj.getString("vc"),
                                    commonObj.getString("ch"),
                                    commonObj.getString("ar"),
                                    commonObj.getString("is_new"),
                                    1L, 0L, 0L, 0L, obj.getJSONObject("page").getLong("during_time"),
                                    obj.getLong("ts"));
        });
        // 标记pv
        final SingleOutputStreamOperator<VisitorStats> pageStatsStream = pageStream.map(json -> {
            final JSONObject obj = JSON.parseObject(json);
            final JSONObject commonObj = obj.getJSONObject("common");
            
            return new VisitorStats("", "",
                                    commonObj.getString("vc"),
                                    commonObj.getString("ch"),
                                    commonObj.getString("ar"),
                                    commonObj.getString("is_new"),
                                    0L, 1L, 0L, 0L, 0L,
                                    obj.getLong("ts"));
        });
        //标记sv 进入次数
        final SingleOutputStreamOperator<VisitorStats> svStatsStream =
            pageStream.flatMap(new FlatMapFunction<String, VisitorStats>() {
                @Override
                public void flatMap(String json, Collector<VisitorStats> out) throws Exception {
                    final JSONObject obj = JSON.parseObject(json);
                    final JSONObject commonObj = obj.getJSONObject("common");
                    
                    final String lastPageId = obj.getJSONObject("page").getString("last_page_id");
                    if (lastPageId == null || lastPageId.length() == 0) {
                        final VisitorStats vs = new VisitorStats("", "",
                                                                 commonObj.getString("vc"),
                                                                 commonObj.getString("ch"),
                                                                 commonObj.getString("ar"),
                                                                 commonObj.getString("is_new"),
                                                                 0L, 0L, 1L, 0L, 0L,
                                                                 obj.getLong("ts"));
                        
                        out.collect(vs);
                    }
                }
            });
        
        // 标记跳出次数
        final SingleOutputStreamOperator<VisitorStats> ujStatsStream = userJumpStream.map(json -> {
            final JSONObject obj = JSON.parseObject(json);
            final JSONObject commonObj = obj.getJSONObject("common");
            return new VisitorStats("", "",
                                    commonObj.getString("vc"),
                                    commonObj.getString("ch"),
                                    commonObj.getString("ar"),
                                    commonObj.getString("is_new"),
                                    0L, 0L, 0L, 1L, 0L,
                                    obj.getLong("ts"));
        });
        
        // 4个流union成一个流
        return uvStatsStream.union(pageStatsStream, svStatsStream, ujStatsStream);
        
    }
}
